/**
 * 题目链接：https://leetcode.cn/problems/intersection-of-two-linked-lists/
 */
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
        next = null;
    }
}

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode curA = headA;
        ListNode curB = headB;
        int lenA = 0;
        int lenB = 0;
        while (curA != null || curB != null) {
            if (curA != null)  {
                lenA++;
                curA = curA.next;
            }
            if (curB != null) {
                lenB++;
                curB = curB.next;
            }
        }
        curA = headA;
        curB = headB;
        int val = lenA-lenB;
        if (val > 0) {
            while (val != 0) {
                curA = curA.next;
                val--;
            }
        }else {
            while (val != 0) {
                curB = curB.next;
                val++;
            }
        }
        while (curA != curB) {
            curA = curA.next;
            curB = curB.next;
        }
        return curA;
    }
}